<template>
  <div>
    <el-card>
      <div slot="header">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
          <el-form-item>
            <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
          </el-form-item>
          <el-form-item label="场次名称" >
            <session-id-select v-model="session"></session-id-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
            <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
            <el-button type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table
            :data="dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;">
          <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
          </el-table-column>
          <el-table-column
              prop="id"
              header-align="center"
              align="center"
              label="秒杀商品id">
          </el-table-column>
          <el-table-column
              prop="productId"
              header-align="center"
              align="center"
              label="商品id">
          </el-table-column>
          <el-table-column
              prop="sessionId"
              header-align="center"
              align="center"
              label="场次id">
          </el-table-column>
          <el-table-column
              prop="seckillPrice"
              header-align="center"
              align="center"
              label="秒杀价格">
          </el-table-column>
          <el-table-column
              prop="seckillCount"
              header-align="center"
              align="center"
              label="秒杀商品数量">
          </el-table-column>
          <el-table-column
              prop="seckillLimit"
              header-align="center"
              align="center"
              label="购买数量最大限制">
          </el-table-column>
          <el-table-column 
              prop="seckillStatus"
              header-align="center"
              align="center"
              label="秒杀状态">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.seckillStatus" active-color="green" inactive-color="red" :active-value="1"
                          :inactive-value="0" @change="updateStatus(scope.row.id, scope.row.seckillStatus)">
                </el-switch>
              </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="150"
              label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="relationDetilsHandle(scope.row.id)">详情</el-button>
              <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
              <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
        <session-details v-if="sessionDetailsVisable" ref="sessionDetails"></session-details>
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
      </div>
    </el-card>
  </div>
</template>

<script>
import AddOrUpdate from './relation-add-or-update'
import SessionDetails from './session-details'
import SessionIdSelect from '../common/sessionId-select.vue'
import request from "@/utils/request";

export default {
  data() {
    return {
      //默认菜单不收缩
      isCollapse: false,
      //侧边栏宽度
      asideWidth: '200px',
      //默认显示图标为收缩图标
      collapseIcon: 'el-icon-s-fold',
      //管理员数据
      admin: {
        name: ''
      },
      session: '',
      dataForm: {
        key: '',
        sessionId: ""
      },
    
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      sessionDetailsVisable: false
    }
  },
  components: {
    AddOrUpdate,SessionDetails,SessionIdSelect
  },
  watch:{
    session:{
      handler(newVal,oldVal){
        this.dataForm.sessionId = newVal
      }
    }
  },
  
  methods: {
    updateStatus(id, seckillStatus) {
      const newStatus = seckillStatus ? 1 : 0
      // 发送请求
      request.put('/seckill/relation/admin/status', {
        id,
        seckillStatus: newStatus
      }).then(res => {
        if (res.data.code === 200) {
          // 找到当前行的索引
          const rowIndex = this.dataList.findIndex(item => item.id === id);

          if (rowIndex !== -1) {
            // 更新当前行的 upStatus 属性
            this.dataList[rowIndex].seckillStatus = seckillStatus;
          }
        }
      });
    },
    //退出登录
    logout() {
      localStorage.removeItem("user")
      this.$router.push(`/login`)
    },

    //控制菜单的左右收缩
    handleCollapse() {
      this.isCollapse = !this.isCollapse
      this.asideWidth = this.isCollapse ? '64px' : '200px'
      this.collapseIcon = this.isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'
    },

    setSessionId(){
      this.$on("sessionId",(res)=>{
        this.dataForm.sessionId = res;
      })
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      request.get('/seckill/relation/admin/list', {
        params: {
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key,
          sessionId: this.dataForm.sessionId
        }
      }).then((response) => {
        if (response.data && response.data.code === 200) {
          this.dataList = response.data.page.list
          this.totalPage = response.data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      }).catch((error) => {
        console.error(error)
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    relationDetilsHandle(id){
      
      this.sessionDetailsVisable = true
      this.$nextTick(() => {
        this.$refs.sessionDetails.forminit(id)
      })
    },
    // 删除
    deleteHandle(id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.post('/seckill/relation/admin/delete', ids, {
          headers: {
            'Content-Type': 'application/json'
          }
        }).then((response) => {
          if (response.data && response.data.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(response.data.msg)
          }
        }).catch((error) => {
          console.error(error)
        })
      })
    }
  },
  created() {
    this.getDataList()
  },
  mounted(){},
  beforeDestroy(){}
}
</script>
